<?php
namespace System\Core;

class Request {
    public function method() {
        return $_SERVER['REQUEST_METHOD'];
    }
    
    public function isGet() {
        return $this->method() === 'GET';
    }
    
    public function isPost() {
        return $this->method() === 'POST';
    }
    
    public function uri() {
        // 修复：正确处理URI，移除index.php部分
        $uri = $_SERVER['REQUEST_URI'] ?? '/';
        
        // 去除查询字符串
        if (($pos = strpos($uri, '?')) !== false) {
            $uri = substr($uri, 0, $pos);
        }
        
        // 标准化URI：去除开头和结尾的斜杠
        $uri = trim($uri, '/');
        
        // 移除index.php部分（如果存在）
        // if (strpos($uri, 'index.php') === 0) {
        //     $uri = substr($uri, strlen('index.php'));
        //     $uri = trim($uri, '/');
        // }
        
        return $uri ?: 'home';
    }
    
    public function get($key = null, $default = null) {
        return $key ? ($_GET[$key] ?? $default) : $_GET;
    }
    
    public function post($key = null, $default = null) {
        return $key ? ($_POST[$key] ?? $default) : $_POST;
    }
    
    public function input($key = null, $default = null) {
        $data = array_merge($_GET, $_POST);
        return $key ? ($data[$key] ?? $default) : $data;
    }

     /**
     * 获取JSON输入
     * 
     * @return array
     */
    public function json() {
        $content = file_get_contents('php://input');
        return json_decode($content, true) ?: [];
    }

     public static function capture() {
        return new self();
    }
    
    // 添加获取客户端IP的方法
    public function ip() {
        $keys = [
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR'
        ];
        
        foreach ($keys as $key) {
            if (!empty($_SERVER[$key])) {
                $ips = explode(',', $_SERVER[$key]);
                return trim($ips[0]);
            }
        }
        
        return $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    }

      /**
     * 检查请求是否期望JSON响应
     * 
     * @return bool
     */
    public function expectsJson() {
        $accept = $_SERVER['HTTP_ACCEPT'] ?? '';
        
        // 检查是否包含application/json
        if (strpos($accept, 'application/json') !== false) {
            return true;
        }
        
        // 检查是否AJAX请求
        if ($this->isXmlHttpRequest()) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 检查是否是AJAX请求
     * 
     * @return bool
     */
    public function isXmlHttpRequest() {
        $header = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '';
        return strtolower($header) === 'xmlhttprequest';
    }

    /**
     * 获取文件
     *
     */
    public function file($name){
        return $_FILES[$name] ?? null;
    }
}